import Utils from '@/utils';
import { $XTrack } from '@/report';
import $http from '@/utils/x-request';
export default {
  namespaced: true,
  state: {
    dialogSubscribeGuide: false // 订阅消息提示是否显示
  },
  mutations: {
    SET_DATA: (state, data) => {
      for (const key in data) {
        state[key] = data[key];
      }
    }
  },
  actions: {
    setData({ commit }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_DATA', data);
        resolve();
      });
    },
    requestSubscribeMessage({ commit, dispatch }, options) {
      return new Promise(async(resolve, reject) => {
        // 判断微信版本是否支持订阅
        if (!uni.requestSubscribeMessage) {
          return reject();
        }
        console.log(options);
        let data = [];
        await dispatch('getTemplateList', options).then((res) => {
          data = res.data || [];
        });
        const availableList = data ? data.map(item => item.templateId) : [];
        const messageTemplateIdList = data ? data.map(item => item.messageTemplateId) : [];
        // 判断用户是否点击过永久授权
        dispatch('isAlways', availableList).then(async(res) => {
          console.log('已全部授权', res);
          if (res) {
            if (availableList.length > 0) {
              uni.requestSubscribeMessage({
                tmplIds: availableList
              });
            }
            // 永久授权后，告诉后台更新数据
            await dispatch('subscribeMessage', {
              storeId: options.storeId,
              subscribeType: options.subscribeType || null,
              subscribeContent: options.subscribeContent || null,
              messageTemplateIdList: messageTemplateIdList
            });
            resolve(true);
            commit('SET_DATA', {
              dialogSubscribeGuide: false
            });
          } else {
            console.log('未全部授权，进行授权操作', availableList);
            if (availableList.length > 0) {
              // 引导图比唤起订阅消息慢
              const timeout = setTimeout(() => {
                commit('SET_DATA', {
                  dialogSubscribeGuide: true
                });
              }, 1000);
              uni.requestSubscribeMessage({
                tmplIds: availableList,
                success: async(res) => {
                  console.log(res);
                  const acceptTemplateIdList = availableList.filter(item => res[item] === 'accept');
                  const isAccept = acceptTemplateIdList.length > 0;
                  if (isAccept) {
                    console.log('用户点击授权');
                    await dispatch('subscribeMessage', {
                      storeId: options.storeId,
                      subscribeType: options.subscribeType || null,
                      subscribeContent: options.subscribeContent || null,
                      messageTemplateIdList: messageTemplateIdList
                    });
                    resolve(true);
                    commit('SET_DATA', {
                      dialogSubscribeGuide: false
                    });
                  } else {
                    $XTrack('subscribeMessageRejectEvent', {
                      messageTemplateIdList: messageTemplateIdList,
                      path: Utils.$getCurrentPage().route
                    });
                    reject();
                    commit('SET_DATA', {
                      dialogSubscribeGuide: false
                    });
                  }
                },
                fail: (err) => {
                  console.warn('uni.requestSubscribeMessage-> ', err);
                  commit('SET_DATA', {
                    dialogSubscribeGuide: false
                  });
                  if (timeout) {
                    clearTimeout(timeout);
                  }
                  // 当接收通知未开启时，进行提示
                  if (err.errCode === 20004) {
                    uni.showToast({
                      title: '请点击右上角，设置 -> 订阅消息 -> 接收通知开启',
                      duration: 3000,
                      icon: 'none'
                    });
                  }
                  $XTrack('requestSubscribeMessageFail', err);
                  reject(err);
                }
              });
            } else {
              reject();
            }
          }
        });
      });
    },
    // 获取订阅消息可订阅模块列表
    getTemplateList({ commit }, data) {
      return new Promise((resolve, reject) => {
        $http({
          method: 'get',
          url: '/marketing/message/template/app/list',
          data: data,
          errType: 'none'
        }).then((res) => {
          try {
            resolve(res);
          } catch (e) {
            console.warn('getTemplateList-> ', e);
          }
        });
      });
    },
    // 告诉服务端发送订阅消息
    subscribeMessage({ commit }, data) {
      return new Promise((resolve, reject) => {
        $http({
          method: 'post',
          url: '/marketing/message/template/subscribe',
          errType: 'none',
          data
        }).then((res) => {
          try {
            // 订阅消息埋点上报
            $XTrack('subscribeMessageEvent', {
              messageTemplateIdList: data.messageTemplateIdList,
              path: Utils.$getCurrentPage().route
            });
            resolve(res);
          } catch (e) {
            console.warn('subscribeMessage-> ', e);
          }
        });
      });
    },
    // 判断用户是否点击过总是允许订阅消息
    isAlways({ commit }, templateId) {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          withSubscriptions: true,
          success: (res) => {
            if (
              res &&
              res.subscriptionsSetting &&
              res.subscriptionsSetting.itemSettings &&
              res.subscriptionsSetting.itemSettings[templateId[0]]
            ) {
              resolve(true);
            } else {
              resolve(false);
            }
          },
          fail: () => {
            reject();
          }
        });
      });
    }
  }
};
